<template>
  <div>
    <!-- <div class="py-[8px] flex gap-[90px] select-wrapper" v-if="props.allowDelete">
      <n-checkbox v-model:checked="selectAll" @update:checked="onSelectAll">
        <div class="text-[18px] font-[500]">{{ $t("button.选择所有") }}</div>
      </n-checkbox>

      <n-popconfirm
        @positive-click="delAll"
        :positive-text="$t('button.确定')"
        :negative-text="$t('button.取消')"
        v-if="productList?.filter((x) => x.selected)?.length > 0"
      >
        <template #trigger>
          <div class="text-[18px] font-[500] cursor-pointer">
            {{ $t("button.删除所选项目") }}
          </div>
        </template>
        {{ $t("confirm.删除商品") }}
      </n-popconfirm>
    </div> -->
    <n-table class="table-wrapper" :bordered="false" single-column>
      <thead>
        <tr class="bg-[red]">
          <th class="">{{ $t("common.商品") }}</th>
          <th class="w-[260px]">{{ $t("common.规格") }}</th>
          <th class="w-[150px]">{{ $t("common.单价") }}</th>
          <th class="w-[120px]">{{ $t("common.数量") }}</th>
          <th class="w-[180px]">
            <div class="pr-[42px] text-right">
              {{ $t("common.金额") }}
            </div>
          </th>
          <th class="w-[120px]" v-if="props.allowDelete">{{ $t("common.操作") }}</th>
        </tr>
      </thead>
      <tbody class="text-[18px] font-[300]">
        <tr
          :class="item.selected ? 'selected' : ''"
          v-for="(item, i) in productList"
          :key="item.id"
        >
          <td>
            <div class="flex gap-[16px] items-center">
              <n-checkbox
                v-model:checked="item.selected"
                v-if="props.allowDelete"
                :disabled="item.isErr"
              >
              </n-checkbox>
              <div
                class="w-[72px] h-[72px] border-solid border-[#AAAAAA] border-[1px] rounded-[5px] overflow-hidden"
              >
                <img class="w-full h-full" :src="item.whiteImage" />
              </div>
              <div
                @click="goInfo(item)"
                class="flex flex-1 text-[#303030] cursor-pointer"
              >
                <n-ellipsis :line-clamp="3" :tooltip="false">
                  {{ item.subject }}
                </n-ellipsis>
              </div>
            </div>
          </td>
          <td class="text-left">
            <div v-if="item.specInfo">
              <div
                class="flex gap-[6px] text-[#303030]"
                v-for="(item, i) in JSON.parse(item.specInfo)"
              >
                <div class="flex-1">{{ item.valueTrans }}</div>
              </div>
            </div>
          </td>
          <td>
            <div class="justify-end flex gap-[8px] items-center px-[16px]">
              <money :money="computedSkuPrice(item)" :is-cny="false"></money>
              <n-popover
                v-if="!props.readonly"
                trigger="hover"
                placement="right"
                @update:show="onShowRangPrice(item)"
              >
                <template #trigger>
                  <n-icon class="text-[16px] cursor-pointer">
                    <HelpCircleOutline></HelpCircleOutline>
                  </n-icon>
                </template>
                <div class="flex">
                  <div
                    class="w-[120px] text-[#5C5C5C] font-[300] text-[16px] leading-[28px]"
                  >
                    <div>{{ $t("common.单价") }}（MXN）</div>
                    <div>{{ $t("common.最小订购量") }}</div>
                  </div>
                  <n-spin :spin="true" v-if="!item.goods"></n-spin>
                  <template v-if="item.goods?.productSaleInfo.quoteType != 1">
                    <div
                      v-for="(r, ri) in item.goods?.productSaleInfo?.priceRangeList"
                      :key="ri"
                      class="w-[120px] text-[#303030] text-[16px] text-center"
                    >
                      <div class="flex">
                        <money class="m-auto" :money="r.price" :is-cny="false"></money>
                      </div>
                      <div class="flex">
                        <div class="flex items-center m-auto">
                          <span>{{ r.startQuantity }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div
                      v-for="(r, ri) in item.goods?.productSkuInfos?.filter(
                        (x) => item.specId == x.specId
                      )"
                      :key="ri"
                      class="w-[120px] text-[#303030] text-[16px] text-center"
                    >
                      <div class="flex">
                        <money
                          class="m-auto"
                          :money="r.consignPrice"
                          :is-cny="false"
                        ></money>
                      </div>
                      <div class="flex">
                        <div class="flex items-center m-auto">
                          <span>{{ item.goods?.minOrderQuantity }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </n-popover>
            </div>
          </td>
          <td>
            <div class="w-[120px] text-center relative">
              <template v-if="props.readonly">
                <div class="text-[18px] flex items-center justify-end text-[#303030]">
                  <div class="text-[18px] flex items-center pr-[32px]">
                    <n-icon>
                      <CloseOutline></CloseOutline>
                    </n-icon>
                    {{ formatMoney(item.quantity, 0) }}
                  </div>
                </div>
              </template>
              <n-spin v-else :show="loadingIds.includes(item.offerId)">
                <n-input-number
                  v-model:value="item.quantity"
                  :min="minComputed(item)"
                  :max="maxComputed(item)" 
                  placeholder=""
                  button-placement="both" 
                  @update:value="onUpdateQuantity(item)"
                />
              </n-spin>

              <div
                v-if="item.isErr"
                class="absolute bottom-[-18px] right-0 w-[200px] text-right text-[14px] text-[--main-color] h-[20px]"
              >
                <!-- {{computedSkuCountError(item)}} -->
                <template v-if="computedSkuCountError(item) == 1">
                  {{ $t("common.最小订购量") }}：
                  {{ minComputed(item) }}
                </template>
                <template v-else-if="computedSkuCountError(item) == 2">
                  Debería ser múltiplo de
                  {{ item.goods?.batchNumber }}.
                </template>
                <template v-if="computedSkuCountError(item) == 3">
                  {{ $t("common.库存") }}：
                  {{ maxComputed(item) }}
                </template>
              </div>
            </div>
          </td>
          <td>
            <div class="justify-end flex px-[30px] text-[#303030]">
              <money :money="item.price * item.quantity" :is-cny="false"></money>
            </div>
          </td>
          <td class="text-center" v-if="props.allowDelete">
            <n-popconfirm
              @positive-click="handlePositiveClick(item)"
              :positive-text="$t('button.确定')"
              :negative-text="$t('button.取消')"
            >
              <template #trigger>
                <n-button quaternary type="error">
                  {{ $t("button.删除") }}
                </n-button>
              </template>
              {{ $t("confirm.删除商品") }}
            </n-popconfirm>
          </td>
        </tr>
      </tbody>
    </n-table>
  </div>
</template>

<script setup>
import { ref, defineModel } from "vue";
import { getCommodityDetail } from "@/api/product";
import { batchUpdate, batchDelete } from "@/api/cart";
import { useMessage } from "naive-ui";
import { useI18n } from "vue-i18n";
import { debounce } from "lodash";
import { HelpCircleOutline, CloseOutline } from "@vicons/ionicons5";
import bus from "@/utils/mitt";
import { formatMoney } from "@/utils/formatMoney";
const { t } = useI18n();
const message = useMessage();
const props = defineProps({
  allowDelete: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
});
const productList = defineModel("productList");
const selectAll = ref(false);
const detailList = ref([]); //商品详情
const loadingIds = ref([]);
const emit = defineEmits(["onUpdate"]);
const goInfo = (goods) => {
  window.open(`/#/goods/${goods.offerId}`, "_blank");
};

const handlePositiveClick = async (item) => {
  await batchDelete([item.specId]);
  emit("onUpdate");
  bus.emit("onUpdateCart");
};

const onSelectAll = (value) => {
  for (let i = 0; i < productList.value.length; i++) {
    const element = productList.value[i];
    element.selected = value;
  }
};

const delSelected = async () => {
  let ids = productList.value.filter((x) => x.selected)?.map((x) => x.specId);
  await batchDelete(ids);
  emit("onUpdate");
  bus.emit("onUpdateCart");
};

/**
 * 获取商品详情 如果已存在则跳过
 */
const loadingPromises = new Map();
const getGoodsInfo = async (item) => {
  // let goods = detailList.value.find((x) => x.offerId == item.offerId);
  // if (goods) return goods;
  if (item.goods) return item.goods;
  // 如果offerId对应的Promise已经存在，直接返回它
  if (loadingPromises.has(item.offerId)) {
    return loadingPromises.get(item.offerId);
  }
  // 创建一个新的Promise
  const promise = new Promise(async (resolve, reject) => {
    try {
      const { data } = await getCommodityDetail(item.offerId);
      // goods = data.data;
      item.goods = data.data;
      // detailList.value.push(goods);
      resolve(item.goods); // 解析Promise，返回goods数据
    } catch (error) {
      reject(error); // 如果有错误，拒绝Promise
    } finally {
      // 清理Map中的条目
      loadingPromises.delete(item.offerId);
    }
  });
  // 将新创建的Promise存入Map
  loadingPromises.set(item.offerId, promise);
  return promise; // 返回Promise，无论它是新创建的还是已存在的
};

// const getGoodsInfo = async (item,callback) => {
//   let goods = detailList.value.find((x) => x.offerId == item.offerId);
//   if (!goods) {
//     if (loadingIds.value.includes(item.offerId)) {
//       return;
//     }
//     loadingIds.value.push(item.offerId);
//     const { data } = await getCommodityDetail(item.offerId);
//     loadingIds.value = loadingIds.value.filter((x) => x != item.offerId);
//     goods = data.data;
//     detailList.value.push(goods);
//   }
//   return goods;
// };
const onUpdateQuantity = async (item) => {
  item.cal = true; //标记当前有商品正在修改数量
  await getGoodsInfo(item);
  // let min = minComputed(item);
  // // let max = maxComputed(item);
  // if (item.quantity < min) {
  //   item.quantity = min;
  //   item.cal = false;
  //   // message.warning(`Este producto se debe comprar en un mínimo de ${min} piezas.`);
  //   return;
  // }

  await debouncedUpdateCart(item);
  item.price = computedSkuPrice(item);
};

const debouncedUpdateCart = debounce(async (item) => {
  // This function will be called after the user stops typing for a certain duration
  if (computedSkuCountError(item) != 0) return;
  loadingIds.value.push(item.offerId);
  await batchUpdate(productList.value);
  loadingIds.value = loadingIds.value.filter((x) => x != item.offerId);
  emit("onUpdate");
  bus.emit("onUpdateCart");
  item.cal = false;
}, 500); // Adjust the time delay as needed (300ms in this case)

const minComputed = (item) => {
  return item.goods?.minOrderQuantity || 1;
};
const maxComputed = (item) => {
  return item.goods?.productSkuInfos?.find((x) => x.specId == item.specId)?.amountOnSale;
};

const batchNumberComputed = (item) => {
  let num = item.goods?.batchNumber;
  return num > 0 ? num : 1;
};

const computedSkuPrice = (item) => {
  // console.log("%c Line:427 🍔 sku", "color:#fca650", sku);
  // 0-无sku按商品数量报价，
  // 1-按sku规格报价
  // 2-有sku按商品数量报价
  let goods = item.goods;
  const type = goods?.productSaleInfo.quoteType;
  if (type == 1) {
    return item.price;
  } else {
    let range = goods?.productSaleInfo.priceRangeList;
    // console.log("%c Line:349 🍏 range", "color:#ea7e5c", range);
    // // 需要判断商品是否支持混批
    // let quantity = computedSkuQuantity(sku.skuAttributes[0]); //sku.quantity;  // 需要计算单个sku的所有数量

    if (item.quantity < goods?.minOrderQuantity) {
      //小于起批量
      return range[0].price;
    }
    if (!range) return item.price; //商品信息未获取到的时候 使用购物车存入的价格
    for (let i = range.length - 1; i >= 0; i--) {
      if (item.quantity >= range[i].startQuantity) {
        return range[i].price;
      }
    }
  }
};

const computedSkuCountError = (sku) => {
  // let goods = detailList.value.find((x) => x.offerId == sku.offerId);
  let goods = sku.goods;
  sku.isErr = true;
  if (sku.quantity == 0 || sku.quantity < minComputed(sku)) {
    return 1;
  }
  if (goods?.batchNumber > 0 && sku.quantity % goods?.batchNumber != 0) {
    // sku.selected = false;  //不能取消勾选
    return 2;
  }
  //判断库存
  if (sku.quantity > maxComputed(sku)) {
    return 3;
  }

  sku.isErr = false;
  return 0;
};

// const onBlurQuantity = (sku) => {
//   let min = minComputed(sku);
//   //1手起批量
//   let batchNumber = goods.value.batchNumber > 0 ? goods.value.batchNumber : 1;
//   if (sku.quantity != 0) {
//     const remainder = sku.quantity % batchNumber;
//     if (remainder !== 0) {
//       // 如果有余数，那么增加 (batchNumber - 余数)，使得总数可以被 batchNumber 整除
//       sku.quantity += batchNumber - remainder;
//     } else if (sku.quantity < min) {
//       sku.quantity = min;
//       // message.warning(`Este producto se debe comprar en un mínimo de ${min} piezas.`);
//     }
//   }
// };

const onShowRangPrice = async (item) => {
  await getGoodsInfo(item);
};

const checkSelected = async () => {
  return new Promise(async (resolve, reject) => {
    let skus = productList.value.filter((x) => x.selected);
    for (const sku of skus) {
      if (!sku.goods) {
        await getGoodsInfo(sku);
      }
      computedSkuCountError(sku);
    }
    if (skus.filter((x) => x.isErr).length > 0) {
      resolve(false);
    } else {
      resolve(true);
    }
  });
};

defineExpose({
  delSelected,
  onSelectAll,
  checkSelected,
});
</script>

<style lang="scss" scoped>
.select-wrapper {
  .n-checkbox {
    align-items: center;
  }
}

.table-wrapper {
  thead {
    th {
      background-color: var(--sub-color);
      color: white;
      text-align: center;
      height: 32px;
      padding: 0;
    }
  }
  .selected {
    td {
      background-color: #fffbf6;
    }
  }
}
</style>
